/**
 *
 */

package it.bd.SetAllConnectionsOff.helper;

import android.content.ContextWrapper;
import android.content.SharedPreferences.Editor;

import it.bd.SetAllConnectionsOff.SetAllConnectionsOff;

import java.util.Map;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public abstract class APreferenceAware<T> {

    public static final String SAVED_STATE_KEY   = "saved";
    public static final String LIMITED_STATE_KEY = "limited";

    abstract ContextWrapper getContext();

    abstract String getPrefKey();

    public void deleteLimitedStateValue() {
        String tempKey = LIMITED_STATE_KEY + "." + getPrefKey();
        deleteValue(tempKey);
    }

    public void deleteSavedStateValue() {
        String tempKey = SAVED_STATE_KEY + "." + getPrefKey();
        deleteValue(tempKey);
    }

    public T getLimitedStateValue() {
        String tempKey = LIMITED_STATE_KEY + "." + getPrefKey();
        return getValue(tempKey);
    }

    public T getSavedStateValue() {
        String tempKey = SAVED_STATE_KEY + "." + getPrefKey();
        return getValue(tempKey);
    }

    public void setLimitedStateValue(T value) {
        String tempKey = LIMITED_STATE_KEY + "." + getPrefKey();
        setValue(tempKey, value);
    }

    public void setSavedStateValue(T value) {
        String tempKey = SAVED_STATE_KEY + "." + getPrefKey();
        setValue(tempKey, value);
    }

    private void deleteValue(String key) {
        Editor editor = getContext().getSharedPreferences(SetAllConnectionsOff.PREF_NAME, 0).edit();
        editor.remove(key);
        editor.commit();
    }

    @SuppressWarnings("unchecked")
    private T getValue(String key) {
        Map<String, ?> prefs = getContext().getSharedPreferences(SetAllConnectionsOff.PREF_NAME, 0).getAll();
        if (prefs.containsKey(key)) {
            try {
                return (T) prefs.get(key);
            } catch (ClassCastException e) {
                // ignore , return null;
            }
        }
        return null;

    }

    private void setValue(String key, T value) {
        Editor editor = getContext().getSharedPreferences(SetAllConnectionsOff.PREF_NAME, 0).edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else
            throw new IllegalArgumentException("Type " + value.getClass().getName() + " not supported ");
        editor.commit();
    }
}
